<?php include("includes/header.php"); ?>

<style>

#advanced_container{
  float: left;
  margin-top: 19px;
  border: 1px solid #5f0808;
  width: 200px;
  padding: 10px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;

}
#advanced_form_title
{
  background-color: #5f0808;
  height: 25px;
  padding: 0 10px 0 10px;
  margin: -10px 0 0 -10px;
  width: 100%;
  text-align: center;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;

}

#advanced_form_title h3
{
  color: #f9f9f9;
  padding: 0px;
  margin: 0px;
}
#advanced_form
{
  margin: 10px auto;
  width: 200px;
}
.side_input
{
  width: 195px;
}
#google_map
{
  float: right;
}

/* CSS for tabs */

#page-wrap {
  width: 950px; 
  margin: 0px auto;
}
.tabs {
  position: relative; 
  width: 700px; 
  float: right;
  overflow: auto;
  min-height: 500px; /* This part sucks */
  margin: 10px 0;
}
.tab {
  float: left;
  padding-top: 20px;
}
.tab label {
  background: #eee; 
  padding: 10px 10px 10px; 10px; 
  border-top: 1px solid #ccc; 
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 4px;
  position: relative;
  cursor: pointer;
}
.tab [type=radio] {
  display: none;   
}
.mapContent {
  position: absolute;
  top: 28px;
  left: 0;
  background: white; /*change to white*/
  right: 0;
  bottom: 0;
  padding: 0px;
  border: 1px solid #ccc; 
  margin-top: 20px;
}
.listContent {
  position: absolute;
  top: 28px;
  left: 0;
  background: white; /*change to white*/
  right: 0;
  bottom: 0;
  border: 1px solid #ccc; 
  margin-top: 20px;
  overflow: auto;
}

[type=radio]:checked ~ label {
  background: white;
  border-bottom: 1px solid white;
  z-index: 3;
}

[type=radio]:checked ~ label ~ .listContent {
  z-index: 2;
}

[type=radio]:checked ~ label ~ .mapContent {
  z-index: 2; 
}

</style>


<!-- Load Google Maps API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyADSk4bKtRqS7mS8LLzHPFi6KuQ7bMJHMw&sensor=false"></script>

<div id="advanced_container">
	<div id="advanced_form_title"><h3>Advanced Search</h3></div> <br/> 
	<form id="advanced_form" action="php/search_handler.php" method="GET">
  		<label>City:</label><br />
  			<input class="side_input" type="search" name="cityInput"/><p></p>
  		<label>Zip code: </label><br />
  			<input class="side_input" type="search" name="zipInput"/><p></p>
  		<label>Vineyard Name:</label><br />
	  		<input class="side_input" type="search" name="vineyardInput"/><p></p>
  		
  		<input type="submit" value="Search" style="float:right; margin-right: 5px;"/><p></p><br />

  	</form>
</div>

<div id="page-wrap">

	<!-- Tabs -->
	<div class="tabs">
	
	  <div class="tab">
	    <input type="radio" id="tab-1" name="tab-group-1" checked>
	        <label for="tab-1">List View</label>
	        <div class="listContent">
	          
	        <?php
			$searchStr = "";
			$space = "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
			$select = "SELECT * FROM Vineyard WHERE";
			
      if(isset($_GET['zipCode'])	|| isset($_GET['cityName'])	 || isset($_GET['stateAbb']) ||
         isset($_GET['zipInput']) || isset($_GET['cityInput']) || isset($_GET['vineyardInput'])){
				
				/* from search bar */
				if(isset($_GET['zipCode']) || isset($_GET['cityName']) || isset($_GET['stateAbb'])){						
					/* query the database */
					if(isset($_GET['zipCode']) && strlen($_GET['zipCode']) != 0){
						$searchStr = $_GET['zipCode'];
						$query = mysqli_query($dbc, "$select zipcode = '$searchStr'");
					}
					else if(isset($_GET['cityName']) && strlen($_GET['cityName']) != 0){
						$searchStr = $_GET['cityName'];
						$query = mysqli_query($dbc, "$select city = '$searchStr'");
					}
					else if(isset($_GET['stateAbb']) && strlen($_GET['stateAbb']) != 0){
						$searchStr = $_GET['stateAbb'];
						$query = mysqli_query($dbc, "$select state = '$searchStr'");
					}
				}
				/* from search field */
				else if(isset($_GET['zipInput']) || isset($_GET['cityInput']) || isset($_GET['vineyardInput'])){
					/* query the database */
					if(isset($_GET['zipInput']) && strlen($_GET['zipInput']) != 0){
						$searchStr = $_GET['zipInput'];
						$query = mysqli_query($dbc, "$select zipcode = '$searchStr'");
					}
					else if(isset($_GET['cityInput']) && strlen($_GET['cityInput']) != 0){
						$searchStr = $_GET['cityInput'];
						$query = mysqli_query($dbc, "$select city = '$searchStr'");
					}
					else if(isset($_GET['vineyardInput']) && strlen($_GET['vineyardInput']) != 0){
						$searchStr = $_GET['vineyardInput'];
						$query = mysqli_query($dbc, "$select name = '$searchStr'");
					}
				}		
				$counter = 0;	
				/*fetch the results and convert to an array*/ 
				while($rows = mysqli_fetch_array($query)){
					/* defin variables from database */
					$name = $rows['name'];
					$address1 = $rows['address_1'];
					$city = $rows['city'];
					$state = $rows['state'];
					$zipcode = $rows['zipcode'];
					$phone = $rows['phone'];
					$vID = $rows['id'];
				  
          /* Get geolocation based on address */
          $fullAddress = $address1 . ', ' . $city . ', ' . $state . ',' . $zipcode;
          $gAddress = str_replace(' ', '+', $fullAddress);
          $gUrl = "http://maps.googleapis.com/maps/api/geocode/xml?address=" . $gAddress . "&sensor=false";
          
          $curl = curl_init();
          curl_setopt($curl, CURLOPT_URL, $gUrl);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
          $geoData = curl_exec($curl);
          $geoData = simplexml_load_string($geoData);
          $geoData = json_encode($geoData);
          $geoData = json_decode($geoData, true);
          
          $names[] = $name;
          $vineyardToolTips[] = "<a style=\"color:#5f0808;\" href=\"vineyard.php?vineyard=" . $vID . "\">" . $name . "</a><br />" . $address1 . "<br />" . $city . ", " . $state . " " . $zipcode;
          if(isset($geoData['result']['geometry']['location']))
          {
            $long[] = $geoData['result']['geometry']['location']['lng'];
            $lat[] = $geoData['result']['geometry']['location']['lat'];
          }
          else
          {
            $long[] = 0;
            $lat[] = 0;
          }
					/* formatting phone string */
					$part1 = substr($phone, 0, 3);
					$part2 = substr($phone, 3, 3);
					$part3 = substr($phone, 6, 4);
					$phone = $part1 . "-" . $part2 . "-" . $part3;
				
					/* counting number of vineyard found */
					$counter++;
				
					/* formatting display info*/
					$vName = "<font color='#5f0808'> $name <br><br> </font>";
					$vName1 = "<a href='vineyard.php?vineyard=$vID'>$vName</a>";
					$vinfo = "<font color='#666'> $space $address1, $city 
						 	      $state, $zipcode <br />$space Phone: $phone </font>";
				  
          if($counter % 2 == 0)
          {
					  echo "<div style=\"background-color:#eee; padding: 10px; font-size:90%; margin-bottom: 0px;\">$counter. $vName1 $vinfo</div>";
          }
          else
          {
            echo "<div style=\"background-color:white; padding: 10px; font-size: 90%; margin-bottom: 0px;\">$counter. $vName1 $vinfo</div>";
          }
				}
				/* formatting vineyard found output */
				$vcounter = (($counter == 1 || $counter ==0) ? "vineyard" : "vineyards");
				$counter = $counter == 0 ? "No" : "$counter";
				
				/* display number of vineyards found */
				echo '<p style="text-align:center; font-size: 90%;">' . $counter . ' vineyards found.';
			}			
      else
      {
        echo "<p style=\"padding:15px; font-size: 90%;\">Use the form to get started!</p>";
      }
			?>
				
	        </div>
	    </div>
	 
	  <div class="tab">
	    <input type="radio" id="tab-2" name="tab-group-1">
	    <label for="tab-2">Map View</label>
	    <div class="mapContent">
	      <div id="google_map" style="width:100%; height:100%"></div>
	    </div>
	  </div> 
	</div> 
</div>

<script>
var map;
var service;
var infowindow;

function initialize() {
  //Grab latitude and longitude of first vineyard returned or if empty, San Diego. 
  var sd = new google.maps.LatLng(<?php if(isset($lat[0])){ echo $lat[0]; } else{ echo "32.676373";}?>,<?php if(isset($long[0])){ echo $long[0]; } else{ echo '-117.04838';}?>)

  //Initialize map 
  map = new google.maps.Map(document.getElementById('google_map'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: sd,
    zoom: 10, 
    maxZoom: 18,
    minZoom: 5
  });
  
  var vineyards = [
    <?php 
    if (isset($lat)) 
    {
		 for($i = 0; $i < count($lat); $i++)
		 {
			if($i != count($lat) - 1)
			{
			  echo '[\'' . $vineyardToolTips[$i] . '\', ' . $lat[$i] . ', ' . $long[$i] . ", '" . $names[$i] . "'],";
			}
			else
			{
			  echo '[\'' . $vineyardToolTips[$i] . '\', ' . $lat[$i] . ', ' . $long[$i] . ", '" . $names[$i] . "']";
			}
		}
    }
    ?>
  ];
  
  var marker, i;

  for(var i = 0; i < vineyards.length; i++)
  {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(vineyards[i][1], vineyards[i][2]),
      map: map,
      title: vineyards[i][3]
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i){
      return function(){
        infowindow.setContent(vineyards[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }
   

  //Request from PlacesService 
  infowindow = new google.maps.InfoWindow();
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

<?php include("includes/footer.php"); ?>
